package com.ifcar.app.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ifcar.app.exception.EmptyStringException;
import com.url.ajax.json.JSONException;
import com.url.ajax.json.JSONObject;

/**
 * 验证工具类
 * @author nxlixa
 *
 */
public class Valid {
	
	/**
	 * 参数为空验证
	 * @param params
	 * @return
	 * @throws JSONException 
	 */
	public static JSONObject paramterMissValid(String... params) throws JSONException{
		JSONObject obj = null;
		
		if(null != params && params.length > 0){
			
			for(String str : params){
				if(StringUtil.isEmptyStr(str)){
					obj = new JSONObject();
					obj.put(EC.ERROR, EC.MSG_PARAMTER_ERROR);
					obj.put(EC.CODE, EC.CODE_PARAMTER_ERROR);
					break;
				}
			}
		}
		
		return obj;
	}
	
	/**
	 * 验证邮箱地址是否合法
	 * 
	 * @param email
	 * @return
	 * @throws EmptyStringException 
	 */
	public static boolean validEmail(String email) throws EmptyStringException {
		if(StringUtil.isEmptyStr(email)){
			throw new EmptyStringException("email is null!");
		}
		String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		Pattern regex = Pattern.compile(check);
		Matcher matcher = regex.matcher(email);
		return matcher.matches();
	}

	/**
	 * 验证电话号码是否合法
	 * 
	 * @param phone
	 * @return
	 * @throws EmptyStringException 
	 */
	public static boolean validPhone(String phone) throws EmptyStringException {
		if(StringUtil.isEmptyStr(phone)){
			throw new EmptyStringException("phone number is null!");
		}
		String check = "^(13[0-9]|15[0-9]|18[0,1,2,3,6,7,8,9])\\d{8}$";
		Pattern regex = Pattern.compile(check);
		Matcher matcher = regex.matcher(phone);
		return matcher.matches();
	}

	/**
	 * 验证密码
	 * @param pwd
	 * @return
	 */
	public static boolean validPassword(String pwd) {
		return null != pwd && pwd.length() >= 6 && pwd.length() <= 30;
	}
	
}
